#!/usr/bin/env python
# -*- coding: utf-8 -*-
# author:梁鸿宇
 
import tkinter as tk  # 使用Tkinter前需要先导入
from PIL import Image, ImageTk
import Method
import os



#==========================================主窗体==========================================#
# 所有控件必须在主窗体里创建，然后调用函数更改其属性时通过参数传入
def Main_Window():
    # 建立窗口window
    window = tk.Tk()
    # 设置主窗口的宽高
    window_width = 1000
    window_height = 500
    # 获取屏幕的分辨率
    screen_width  = window.winfo_screenwidth()
    screen_height = window.winfo_screenheight()
    # 计算主窗口在屏幕上的坐标
    window_x = int((screen_width - window_width)/ 2)
    window_y = int((screen_height - window_height) / 2)

    window.geometry("%sx%s+%s+%s" % (window_width, window_height, window_x, window_y))
    window.title('大牛专属视频下载器')
    window.resizable(width=False, height=False)
    window['bg'] = 'green'
    
    #==========================================搜索帧==========================================#
    search_frame = tk.Frame(window)
    search_frame.place(x = 0, y = 0, width = 1000, height = 40)

    # 输入框初始化
    global search_input
    search_input = tk.Entry(search_frame, width = 40, cursor='plus', font = ('Consolas', '14', 'bold'),bg='#FFFFFF',fg='#0101DF',relief='sunken',bd=4)
    search_input.insert(0, "输入 电视剧/电影/动画 名称")
    search_input.bind("<Key>", search_input_ready)
    search_input.focus_set()
    search_input.pack(side = 'left')

    search_button = tk.Button(search_frame, width = 8, text='搜索', font=('宋体', 14),command=lambda:Search(search_input),relief='ridge',fg='#000000',bg='#D8D8D8')
    search_button.pack(side = 'left')

    # 上下页控制
    prev_button = tk.Button(search_frame, width = 8, text='上一页', font=('宋体', 14),command=lambda:Change_Page(0),relief='ridge',fg='#000000',bg='#D8D8D8')
    prev_button.pack(side = 'left')
    next_button = tk.Button(search_frame, width = 8, text='下一页', font=('宋体', 14),command=lambda:Change_Page(1),relief='ridge',fg='#000000',bg='#D8D8D8')
    next_button.pack(side = 'left')

    # 显示当前页码
    global Page_String
    Page_String = tk.StringVar()
    Page_String.set("当前第 1 页 总共 1 页")
    current_page = tk.Label(search_frame, textvariable = Page_String)
    current_page.pack(side = 'left')

    #==========================================搜索帧==========================================#
    
    
    #==========================================信息展示帧==========================================#
    # 这个帧用来显示信息，包含三个横排的子帧
    Info_frame = tk.Frame(window)
    Info_frame.place(x = 0, y = 40, width = 1000, height = 460)
    # 三个横排的帧，每帧展示一个搜索结果的信息
    Result_frame_Left = tk.Frame(Info_frame)
    Result_frame_Mid = tk.Frame(Info_frame)
    Result_frame_Right = tk.Frame(Info_frame)
    Result_frame_Left.pack(side = 'left', padx = 0, fill = 'both', expand = 'y')
    Result_frame_Mid.pack(side = 'left', padx = 0, fill = 'both', expand = 'y')
    Result_frame_Right.pack(side = 'left', padx = 0, fill = 'both', expand = 'y')

    #==========================================信息展示帧==========================================#

    
    #==========================================左   信息子帧控件排布==========================================#
    # 横排子帧左上角是图片，图片右边是下载按钮、下载选项和下载信息，上两块整体的下方用于显示搜索返回的字符串
    
    Label_Image_Show_Left = tk.Label(Result_frame_Left)  # 用于显示图片
    Label_Image_Show.append(Label_Image_Show_Left)
    Text_Search_Info_Left = tk.Text(Result_frame_Left, wrap = 'word', bg = '#CEF6D8',padx=4,pady=4,relief='solid',spacing1=8,font=('Consolas','12'))  # 用于显示搜索信息
    Text_Search_Info.append(Text_Search_Info_Left)
    Text_Download_Info_Left = tk.Text(Result_frame_Left, wrap = 'word', bg = '#CEF6D8')  # 用于显示下载信息

    # 下载选项单选按钮的绑定变量
    Var_Rbtn_Left = tk.IntVar()
    Var_Rbtn_Left.set(0)

    # 下载按钮、下载选项按钮
    Btn_Download_Left = tk.Button(Result_frame_Left, text = '点击下载')
    Rbtn_Download_Setting_All_Left = tk.Radiobutton(Result_frame_Left, text = '全部下载', value = 0, variable = Var_Rbtn_Left)
    Rbtn_Download_Setting_Part_Left = tk.Radiobutton(Result_frame_Left, text = '部分下载', value = 1, variable = Var_Rbtn_Left)

    # 滚动条绑定Text
    Scorll_Search_Info_Left = tk.Scrollbar(Result_frame_Left)
    Scorll_Search_Info_Left.config(command = Text_Search_Info_Left.yview)
    Text_Search_Info_Left.config(yscrollcommand = Scorll_Search_Info_Left.set)
    Scorll_Download_Info_Left = tk.Scrollbar(Result_frame_Left)
    Scorll_Download_Info_Left.config(command = Text_Download_Info_Left.yview)
    Text_Download_Info_Left.config(yscrollcommand = Scorll_Download_Info_Left.set)

    # 横排子帧内控件相对于帧以绝对位置摆放
    Label_Image_Show_Left.place(x = 0, y = 0, width = 110, height = 150)
    
    Btn_Download_Left.place(x = 110, y = 0, width = 190, height = 20)
    Rbtn_Download_Setting_All_Left.place(x = 110, y = 20, width = 95, height = 20)
    Rbtn_Download_Setting_Part_Left.place(x = 206, y = 20, width = 95, height = 20)
    
    Text_Search_Info_Left.place(x = 110, y = 40, width = 190, height = 110)
    Text_Search_Info_Left.place(x = 2, y = 150, width = 300, height = 300)
    
    Scorll_Download_Info_Left.place(x = 300, y = 40, width = 10, height = 110)
    Scorll_Search_Info_Left.place(x = 300, y = 150, width = 10, height = 300)
    #==========================================左   信息子帧控件排布==========================================#

    #==========================================中   信息子帧控件排布==========================================#
    # 横排子帧左上角是图片，图片右边是下载按钮、下载选项和下载信息，上两块整体的下方用于显示搜索返回的字符串
    
    Label_Image_Show_Mid = tk.Label(Result_frame_Mid)  # 用于显示图片
    Label_Image_Show.append(Label_Image_Show_Mid)
    Text_Search_Info_Mid = tk.Text(Result_frame_Mid, wrap = 'word', bg = '#CEF6D8',padx=4,pady=4,relief='solid',spacing1=8,font=('Consolas','12'))  # 用于显示搜索信息
    Text_Search_Info.append(Text_Search_Info_Mid)
    Text_Download_Info_Mid = tk.Text(Result_frame_Mid, wrap = 'word', bg = '#CEF6D8')  # 用于显示下载信息

    # 下载选项单选按钮的绑定变量
    Var_Rbtn_Mid = tk.IntVar()
    Var_Rbtn_Mid.set(0)

    # 下载按钮、下载选项按钮
    Btn_Download_Mid = tk.Button(Result_frame_Mid, text = '点击下载')
    Rbtn_Download_Setting_All_Mid = tk.Radiobutton(Result_frame_Mid, text = '全部下载', value = 0, variable = Var_Rbtn_Mid)
    Rbtn_Download_Setting_Part_Mid = tk.Radiobutton(Result_frame_Mid, text = '部分下载', value = 1, variable = Var_Rbtn_Mid)

    # 滚动条绑定Text
    Scorll_Search_Info_Mid = tk.Scrollbar(Result_frame_Mid)
    Scorll_Search_Info_Mid.config(command = Text_Search_Info_Mid.yview)
    Text_Search_Info_Mid.config(yscrollcommand = Scorll_Search_Info_Mid.set)
    Scorll_Download_Info_Mid = tk.Scrollbar(Result_frame_Mid)
    Scorll_Download_Info_Mid.config(command = Text_Download_Info_Mid.yview)
    Text_Download_Info_Mid.config(yscrollcommand = Scorll_Download_Info_Mid.set)

    # 横排子帧内控件相对于帧以绝对位置摆放
    Label_Image_Show_Mid.place(x = 0, y = 0, width = 110, height = 150)
    
    Btn_Download_Mid.place(x = 110, y = 0, width = 190, height = 20)
    Rbtn_Download_Setting_All_Mid.place(x = 110, y = 20, width = 95, height = 20)
    Rbtn_Download_Setting_Part_Mid.place(x = 206, y = 20, width = 95, height = 20)
    
    Text_Search_Info_Mid.place(x = 110, y = 40, width = 190, height = 110)
    Text_Search_Info_Mid.place(x = 2, y = 150, width = 300, height = 300)
    
    Scorll_Download_Info_Mid.place(x = 300, y = 40, width = 10, height = 110)
    Scorll_Search_Info_Mid.place(x = 300, y = 150, width = 10, height = 300)
    #==========================================中   信息子帧控件排布==========================================#


    #==========================================右   信息子帧控件排布==========================================#
    # 横排子帧左上角是图片，图片右边是下载按钮、下载选项和下载信息，上两块整体的下方用于显示搜索返回的字符串
    
    Label_Image_Show_Right = tk.Label(Result_frame_Right)  # 用于显示图片
    Label_Image_Show.append(Label_Image_Show_Right)
    Text_Search_Info_Right = tk.Text(Result_frame_Right, wrap = 'word', bg = '#CEF6D8',padx=4,pady=4,relief='solid',spacing1=8,font=('Consolas','12'))  # 用于显示搜索信息
    Text_Search_Info.append(Text_Search_Info_Right)
    Text_Download_Info_Right = tk.Text(Result_frame_Right, wrap = 'word', bg = '#CEF6D8')  # 用于显示下载信息

    # 下载选项单选按钮的绑定变量
    Var_Rbtn_Right = tk.IntVar()
    Var_Rbtn_Right.set(0)

    # 下载按钮、下载选项按钮
    Btn_Download_Right = tk.Button(Result_frame_Right, text = '点击下载')
    Rbtn_Download_Setting_All_Right = tk.Radiobutton(Result_frame_Right, text = '全部下载', value = 0, variable = Var_Rbtn_Right)
    Rbtn_Download_Setting_Part_Right = tk.Radiobutton(Result_frame_Right, text = '部分下载', value = 1, variable = Var_Rbtn_Right)

    # 滚动条绑定Text
    Scorll_Search_Info_Right = tk.Scrollbar(Result_frame_Right)
    Scorll_Search_Info_Right.config(command = Text_Search_Info_Right.yview)
    Text_Search_Info_Right.config(yscrollcommand = Scorll_Search_Info_Right.set)
    Scorll_Download_Info_Right = tk.Scrollbar(Result_frame_Right)
    Scorll_Download_Info_Right.config(command = Text_Download_Info_Right.yview)
    Text_Download_Info_Right.config(yscrollcommand = Scorll_Download_Info_Right.set)

    # 横排子帧内控件相对于帧以绝对位置摆放
    Label_Image_Show_Right.place(x = 0, y = 0, width = 110, height = 150)
    
    Btn_Download_Right.place(x = 110, y = 0, width = 190, height = 20)
    Rbtn_Download_Setting_All_Right.place(x = 110, y = 20, width = 95, height = 20)
    Rbtn_Download_Setting_Part_Right.place(x = 206, y = 20, width = 95, height = 20)
    
    Text_Search_Info_Right.place(x = 110, y = 40, width = 190, height = 110)
    Text_Search_Info_Right.place(x = 2, y = 150, width = 300, height = 300)
    
    Scorll_Download_Info_Right.place(x = 300, y = 40, width = 10, height = 110)
    Scorll_Search_Info_Right.place(x = 300, y = 150, width = 10, height = 300)
    #==========================================右   信息子帧控件排布==========================================#

    
    
    # 主窗口循环显示
    window.mainloop()
    
#==========================================主窗体==========================================#



#==========================================回调函数==========================================#
# 搜索按钮事件函数
def Search(search_input):
    global search_result
    global Result_Num
    global Page_Num
    global User_Search_Count
    global User_Input_Available

    search_string=search_input.get() #获取文本框内容
    if 0 !=User_Input_Available and 0 != len(search_string):
        # 记录系统搜索的次数        emmm搜索只有零次和多次，就1/0吧
        User_Search_Count = 1
        search_result = Method.search(search_string)  # 这是所有搜索结果信息的列表，应定义成全局
        Result_Num = len(search_result)     # 计算搜索结果数
        Page_Num = int(Result_Num / 3) + Result_Num % 3     # 计算页数
        
        # 调用图片刷新函数
        Flash_Page()

    return
      

# 用于刷新页面
def Flash_Page():
    # 子函数用到的全局变量都要声明一下
    global Page_Index
    global Page_String
    global Result_Num
    global Page_Num

    # 清一下图片缓存
    img_show.clear()
    # 图片清除
    Clear_Image()
    # 文字清除
    Clear_Text()

    # 页索引超出最大值最小值，回卷，重置页索引和信息索引
    if Page_Index > Page_Num:
        Page_Index = 1
    if Page_Index <= 0:
        Page_Index = Page_Num
    
    Page_String.set("当前第 %s 页  总共 %s 页" % (Page_Index, Page_Num))

    # 针对当前页页索引计算需要显示信息的索引
    if (Page_Index * 3) <= Result_Num:
        Index = (Page_Index - 1) * 3
        Info_List = search_result[Index:Index+3]
        print("当前页不是末页")
    else:
        Info_Num_Of_Page = Page_Index * 3 - Result_Num      # 末页的信息条数
        Index = (Page_Index - 1) * 3
        Info_List = search_result[Index:Index+Info_Num_Of_Page] 
        print("当前末页")
    
    for Info in Info_List:
        index = Info_List.index(Info)
        Image_Show(Info, index, Text_Search_Info[index])

    return

# 上下页响应函数
def Change_Page(flag):
    global Page_Index
    global User_Search_Count
    if User_Search_Count:
        if flag:     # 下一页----flag==1
            Page_Index = Page_Index + 1
            Flash_Page()
        else:        # 上一页----flag==0
            Page_Index = Page_Index - 1
            Flash_Page()

    return

# 清除信息显示的文字
def Clear_Text():
    # 文字清除
    for i in Text_Search_Info:
        i.configure(state='normal')
        i.delete('1.0', 'end')
        i.configure(state='disable')

# 清除图片显示的图片
def Clear_Image():
    for i in Label_Image_Show:
        i.configure(iamge = None)



# Frame中图片显示函数
def Image_Show(Info, index, Text_Search_Info):
    # 解析传进来的搜索结果
    if len(Info):
        display_string = Method.get_detail(Info)
        Text_Search_Info.configure(state='normal')
        Text_Search_Info.delete('1.0', 'end')
        Text_Search_Info.insert('end', display_string)
        Text_Search_Info.configure(state='disabled')

        # 获取展示图片
        img_url = Info[2]
        headers = {
                'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.106 Safari/537.36'
            }
        img_content = Method.get_response(img_url, headers).content
        if not os.path.exists('./temp/'):
            os.mkdir('./temp/')
        with open('./temp/' + img_url.split('/')[-1] + '.jpeg', 'wb') as f:
            f.write(img_content)
        img = Image.open('./temp/' + img_url.split('/')[-1] + '.jpeg')
        img = img.resize((110, 150), Image.ANTIALIAS)

        img_show.append(ImageTk.PhotoImage(image = img))
        # Label_Image_Show[index].config(image = img_show)
        Label_Image_Show[index].configure(image = img_show[index])
        #print(index)
    else:
        Text_Search_Info.insert('end', "没有找到符合的结果")

    return


# 初始化之后开始输入，将提示词删除
# global search_input_ready
def search_input_ready(event):
    global User_Input_Available
    if search_input.get() == "输入 电视剧/电影/动画 名称":
        search_input.delete(0, 'end')
        User_Input_Available = 1

    return

#==========================================回调函数==========================================#


 
if __name__ == "__main__":
    # 左中右用于显示图片的Label和用于显示描述信息的Text控件     全局变量
    global Label_Image_Show_Left, Text_Search_Info_Left
    global Label_Image_Show_Mid, Text_Search_Info_Mid
    global Label_Image_Show_Right, Text_Search_Info_Right

    # 显示图片和描述信息的控件的列表    全局变量
    global Label_Image_Show
    Label_Image_Show = []
    global Text_Search_Info
    Text_Search_Info = []

    # 当前页面所显示的图片数据流列表    全局变量
    global img_show
    img_show = []

    # 关于页面刷新的全局变量
    global Result_Num         # 搜索到的信息的总数
    global Page_Num           # 分页，Result_num/3，Result_num % 3，每页存放3条信息
    global Page_Index         # 当前页的索引
    Result_Num = 0
    Page_Num = 1
    Page_Index = 1

    # 用于统计用户搜索的次数
    global User_Search_Count
    User_Search_Count = 0

    # 用于标记用户是输入了再搜索
    global User_Input_Available
    User_Input_Available = 0
    
    
    Main_Window()







